#!/usr/bin/env python

import os
import stat
import tarfile

class TemplateManager ( object ):
	def __init__ ( self, mantux, base_root ):
		self._mantux = mantux
		self._root = base_root	# Typically the directory where the ".mantux" dir is hold 

	def scan ( self, destfile ):
		my_dir = os.getcwd ()

		tar = tarfile.open ( destfile, "w:bz2" ) 

		os.chdir ( self._root )
		self._scan ( ".", tar )

		os.chdir ( my_dir )

	def extract ( self, source, destdir ):
		os.chdir ( destdir )

		print "SOURCE: ", source 
		tar = tarfile.open ( source, "r:bz2" )
		tar.extractall ()
		tar.close ()

	def _scan ( self, path, tar ):
		for f in os.listdir ( path ):
			full_name = os.path.join ( path, f )

			st = os.lstat ( full_name )

			if stat.S_ISDIR ( st.st_mode ):
				dname = full_name.replace ( "./", "" )
				
				if self._mantux.exclude ( dirname = dname ):
					continue
				else:	
					self._scan ( full_name, tar )	
					continue
			
			tar.add ( full_name )

def cmd_template_create ( self, args ):
	if not args [ 'name' ]:
		print "ERROR: please specify template name with '--name'"
		return

	name = args [ 'name' ]
	path = os.path.expanduser ( args.get ( "path", "." ) )
	dest = os.path.expanduser ( args.get ( "dest_dir", "~/.mantux/templates" ) )

	if not os.path.exists ( dest ):
		print "ERROR: directory '%s' does not exist" % dest
		return

	t = TemplateManager ( self, path )

	t.scan ( os.path.join ( dest, name + ".tpl" ) )

def cmd_template_install ( self, args ):
	if 'name' not in args:
		print "ERROR: please specify template name with '--name'"
		return

	name = args [ 'name' ]
	name = name.replace ( ".tpl", "" )
	if not name.startswith ( "/" ):
		name = os.path.join ( os.path.expanduser ( "~/.mantux/templates" ), name + ".tpl" )

	destdir = args.get ( "dest_dir", "." )

	t = TemplateManager ( self, destdir )
	t.extract ( name, destdir )

	self.call ( "reinstall" )

def cmd_template_list ( self, args ):
	pass

def install_commands ( mantux ):
	cmds = [
		{ "name" : "template_create",  "func" : cmd_template_create, "params" : [ 
				( "--name", dict ( help = "Repository name" ) ), 
				( "--dest-dir", dict ( help = "Destination dir (defaults in ``.mantux/templates``)" ) ) 
		] },
		{ "name" : "template_install", "func" : cmd_template_install,  "params" : [
				( "--name", dict ( help = "Template name to install" ) ),
				( "--dest-dir", dict ( help = "Directory where to install the template to (defaults to ``.``)" ) )
		] },
		{ "name" : "template_list",    "func" : cmd_template_list,     "params" : "" },
		
	]

	for c in cmds:
		mantux.commands [ c [ 'name' ] ] = c



if __name__ == '__main__':
	tm = TemplateManager ( "/ramdisk/liwe2" )

	try:
		os.unlink ( "/ramdisk/aaa.tar.bz2" )
	except:
		pass

	tm.scan ( "/ramdisk/template_example.tar.bz2" )
